<template>
	<view class="container">
		<view class="cu-nav-bar">
			<uni-nav-bar statusBar color="#ffffff" backgroundColor="#07c160" left-icon="left" @clickLeft="goBack"
				title="备份与恢复" />
		</view>
		<!-- 内容 -->
		<view class="file-opt">
			<button class="export" @click="saveData">导出备份数据</button>
			<button class="import" @click="getFileList">刷新备份列表</button>
		</view>
		<view class="export-msg" v-if="exportFilePath">
			导出成功!文件路径：{{exportFilePath}}
		</view>
		<view class="scroll-view">
			<view class="file-list" v-if="fileList.length > 0">
				<view class="file-item" v-for="item, index in fileList" :key="index">
					<text class="file-item-name">{{item}}</text>
					<view class="file-item-opt">
						<text class="file-item-opt opt-del" @click="deleteData(item)">删除</text>
						<text class="file-item-opt opt-reset" @click="readData(item)">恢复</text>
					</view>
				</view>
			</view>
			<view class="file-list no-data" v-else>
				暂无备份记录
			</view>
		</view>
		<view class="tip-msg">
			提示：如果需要使用其他设备上的数据，请将要备份文件放入备份文件夹，备份文件夹路径为：{{importFilePath}} （如果downloads文件夹不存在,请自行创建）
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		getNowDateTime2
	} from '@/utils/utils'
	import {
		deleteFile,
		getBackupList,
		readFile,
		saveFile
	} from '@/utils/file-utils';

	// 导出文件所在路径
	const exportFilePath = ref('')
	// 导入文件放置路径
	const importFilePath = ref('/storage/emulated/0/Android/data/uni.zjw.cashbook/downloads/')
	const importFilePath_1 = ref('/storage/emulated/0/Android/data/uni.zjw.cashbook/downloads/')
	const importFilePath_2 = ref('/storage/emulated/0/Android/data/io.dcloud.HBuilder/downloads/')
	// 已备份文件
	const fileList = ref([])

	onLoad(() => {
		getFileList(false, false)
	})

	// 读取缓存并封装对象
	const getDataAndformat = () => {
		// 收支记录表
		let cash_log_list = uni.getStorageSync('db_cash_log')
		if (!cash_log_list) {
			cash_log_list = []
		}
		// 收支分类表
		let cash_type_list = uni.getStorageSync('db_cash_type')
		if (!cash_type_list) {
			cash_type_list = []
		}
		// 账户表
		let cash_account_list = uni.getStorageSync('db_cash_account')
		if (!cash_account_list) {
			cash_account_list = []
		}
		// 月账户净资产统计表
		let account_total_month_list = uni.getStorageSync('db_account_total_month')
		if (!account_total_month_list) {
			account_total_month_list = []
		}
		let dataJson = {
			'cash_log_list': cash_log_list,
			'cash_type_list': cash_type_list,
			'cash_account_list': cash_account_list,
			'account_total_month_list': account_total_month_list,
		}
		return JSON.stringify(dataJson)
	}

	// 解析txt文件内容，并保存到缓存
	const readTextToData = (content) => {
		let dataJson = JSON.parse(content)
		if (dataJson.cash_log_list && dataJson.cash_type_list &&
			dataJson.cash_account_list && dataJson.account_total_month_list) {
			// 收支记录表
			uni.setStorageSync('db_cash_log', dataJson.cash_log_list)
			// 收支分类表
			uni.setStorageSync('db_cash_type', dataJson.cash_type_list)
			// 账户表
			uni.setStorageSync('db_cash_account', dataJson.cash_account_list)
			// 月账户净资产统计表
			uni.setStorageSync('db_account_total_month', dataJson.account_total_month_list)
			uni.showToast({
				icon: 'none',
				title: '数据已恢复'
			})
		} else {
			uni.showToast({
				icon: 'error',
				title: '数据不完整'
			})
		}
	}

	// 导出备份数据
	const saveData = () => {
		let fileName = getNowDateTime2() + '.txt'
		let content = getDataAndformat();
		saveFile(fileName, content).then(savePath => {
			exportFilePath.value = savePath
			uni.showToast({
				icon: 'none',
				title: '导出成功'
			})
			getFileList(false)
		}).catch(msg => {
			uni.showToast({
				icon: 'error',
				title: msg
			})
		})
	}

	// 获取备份列表
	const getFileList = (clearMsg = true, toast = true) => {
		if (clearMsg) {
			exportFilePath.value = ''
		}
		let folderPath = importFilePath.value
		getBackupList(folderPath).then(res => {
			res.sort((a, b) => b > a ? 1 : -1)
			fileList.value = res
			if (toast) {
				uni.showToast({
					icon: 'none',
					title: res.length == 0 ? '无备份记录' : '列表已刷新'
				})
			}
		}).catch(msg => {
			folderPath = importFilePath_2.value
			getBackupList(folderPath).then(res => {
				res.sort((a, b) => b > a ? 1 : -1)
				fileList.value = res
				importFilePath.value = importFilePath_2.value
				if (toast) {
					uni.showToast({
						icon: 'none',
						title: res.length == 0 ? '无备份记录' : '列表已刷新'
					})
				}
			}).catch(msg => {
				if (toast) {
					uni.showToast({
						icon: 'error',
						title: msg
					})
				}
			})
		})
	}

	// 还原数据
	const readData = (item) => {
		// 弹出提示框
		uni.showModal({
			title: '提示',
			content: '确定要恢复数据为' + item + '吗？',
			cancelText: '取消',
			cancelColor: '#ff0000',
			confirmText: '确认',
			cancelColor: '#07c160',
			success: (res) => {
				if (res.confirm) {
					exportFilePath.value = ''
					readFile(importFilePath.value + item).then(content => {
						readTextToData(content)
					}).catch(msg => {
						uni.showToast({
							icon: 'error',
							title: msg
						})
					})
				} else if (res.cancel) {
					return
				}
			},
		})
	}

	// 删除数据
	const deleteData = (item) => {
		// 弹出提示框
		uni.showModal({
			title: '提示',
			content: '确定要删除数据' + item + '吗？',
			cancelText: '取消',
			cancelColor: '#ff0000',
			confirmText: '确认',
			cancelColor: '#07c160',
			success: (res) => {
				if (res.confirm) {
					exportFilePath.value = ''
					deleteFile(importFilePath.value + item).then(content => {
						getFileList(true, false)
						uni.showToast({
							icon: 'none',
							title: content
						})
					}).catch(msg => {
						uni.showToast({
							icon: 'error',
							title: msg
						})
					})
				} else if (res.cancel) {
					return
				}
			},
		})
	}

	// 返回
	const goBack = () => {
		uni.navigateBack()
	}
</script>

<style lang="scss">
	@import url("backup_data.css");
</style>